package com.jk1.bianligou.blg.interceptor;

import com.jk1.bianligou.blg.common.ErrorCode;
import com.jk1.bianligou.blg.domain.po.User;
import com.jk1.bianligou.blg.exception.BizException;
import com.jk1.bianligou.blg.mapper.UserMapper;
import com.jk1.bianligou.blg.utils.ThrowUtils;
import com.jk1.bianligou.blg.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WHH
 * 登录检测拦截器
 */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    //登录检测
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        //获取userId查询是否存在
        Long loginUserId;
        try {
            loginUserId = UserUtils.getLoginUserId(request);
        } catch (Exception e) {
            throw new BizException(ErrorCode.NOT_LOGIN_ERROR);
        }
        User user = userMapper.selectById(loginUserId);
        ThrowUtils.throwIfParamsIsNull(user);
        return true;
    }
}
